package me.evis.mobile.sms2cal;

import java.util.ArrayList;
import java.util.Date;

import me.evis.mobile.sms2cal.model.SmsData;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.SmsMessage;
import android.util.Log;

public class SmsReceiver extends BroadcastReceiver {
    /** Tag string for debug logs */
    private static final String TAG = "me.evis.mobile.sms2cal.SmsReceiver";
    
    public static final String SMS_DATA_EXTRA = "me.evis.mobile.sms2cal.SMS_DATA";

    /**
     * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
     */
    @Override
    public void onReceive(final Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras == null)
            return;

        Object[] pdus = (Object[]) extras.get("pdus");

        // ArrayList implements interface Serializable
        final ArrayList<SmsData> smsDatas = new ArrayList<SmsData>();
        for (int i = 0; i < pdus.length; i++) {
            SmsMessage message = SmsMessage.createFromPdu((byte[]) pdus[i]);
            String fromAddress = message.getOriginatingAddress();
            String fromDisplayName = fromAddress;

            Uri uri;
            String[] projection;

            // If targeting Donut or below, use
            // Contacts.Phones.CONTENT_FILTER_URL and
            // Contacts.Phones.DISPLAY_NAME
            uri = Uri.withAppendedPath(
                    ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
                    Uri.encode(fromAddress));
            projection = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME };

            // Query the filter URI
            Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst())
                    fromDisplayName = cursor.getString(0);

                cursor.close();
            }

            SmsData sms = new SmsData();
            sms.from = fromAddress;
            sms.fromDisplayName = fromDisplayName;
            sms.messageBody = message.getMessageBody().toString();
            sms.receiveOn = new Date(message.getTimestampMillis());
            
            smsDatas.add(sms);
            Log.d(TAG, "SMS from " + sms.from + " on " + sms.receiveOn + "added to parse queue.");

        }
        
        // Delegate to service to parse.
        Intent service = new Intent();
        service.setClass(context, SmsParseService.class);
        service.putExtra(SMS_DATA_EXTRA, smsDatas);
        context.startService(service);
    }
}
